package edu.just.pet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter{

    private String dispatchUrl = "";
    private String excludeUrl1 = "";
    private String excludeUrl2 = "";
    private String excludeUrl3="";
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)arg0;
        HttpServletResponse response =(HttpServletResponse)arg1;
        String servletPath = request.getServletPath();

        HttpSession session = request.getSession();
        Object sysUser = session.getAttribute("sysLoginName");
        Object user=session.getAttribute("userLoginName");
        String status=String.valueOf(session.getAttribute("status"));
        System.out.println(servletPath.contains(status));

        /*登陆界面和登陆方法不进行过滤*/
        if(servletPath.equals(dispatchUrl) || servletPath.equals(excludeUrl1)
                ||servletPath.equals(excludeUrl2)||servletPath.contains("front")||servletPath.equals(excludeUrl3)){
            arg2.doFilter(arg0, arg1);
        }else{
            if (sysUser != null && servletPath.contains(status)) {
                arg2.doFilter(arg0, arg1);
            } else if (user !=null && servletPath.contains(status)) {
                arg2.doFilter(arg0, arg1);
            } else{
                response.sendRedirect(request.getContextPath()+dispatchUrl);
            }

        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        dispatchUrl = arg0.getInitParameter("dispatchUrl");
        excludeUrl1 = arg0.getInitParameter("excludeUrl1");
        excludeUrl2 = arg0.getInitParameter("excludeUrl2");
        excludeUrl3 = arg0.getInitParameter("excludeUrl3");
    }

}